package com.jinyuan.service;

import org.apache.http.HttpStatus;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.android.threadpool.IActivity;
import com.android.threadpool.Task;
import com.android.threadpool.TaskOperate;
import com.jinyuan.R;
import com.jinyuan.options.LeftMenuActivity;
import com.jinyuan.options.homepage.service.HomePageService;
import com.jinyuan.options.update.service.UpdateService;
import com.jinyuan.utils.NetUtils;

public class ClientTask implements TaskOperate {

	private static final String KEY = "ClassName";

	@Override
	public void operate(Task task) {
		Message message = handler.obtainMessage();
		message.what = task.getId();
		Bundle bundle = new Bundle();
		bundle.putString(KEY, task.getClassName());
		message.setData(bundle);
		switch (task.getId()) {
		case TaskID.TASK_LOGIN:
		case TaskID.TASK_REGISTER:
			ParentHandlerService.postGeneralMethod(task, message);
			break;
		case TaskID.TASK_LOGOUT:
			ParentHandlerService.getGeneralMethod(task, message);
			break;
		case TaskID.TASK_UPDATE_CHECK:
			UpdateService.getServerVersionInfo(task, message);
			break;
		case TaskID.TASK_UPDATE_DOWNLOAD:
			UpdateService.getDownLoadFile(task, message);
			break;
		case TaskID.TASK_HOMEPAGE:
			HomePageService.getHomePage(task, message);
			break;
		default:
			break;
		}
		handler.sendMessage(message);
	}

	public Handler handler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			String className = msg.getData().getString(KEY);
			// System.out.println("---className---" + className);
			IActivity iActivity = MobileApplication
					.getActivityByName(className);
			int statusCode = msg.getData().getInt(NetUtils.StatusCode);
			// System.out.println("---statusCode---" + statusCode);
			switch (statusCode) {
			case HttpStatus.SC_OK:
				iActivity.refresh(msg.what, msg.obj);
				break;
			case HttpStatus.SC_FORBIDDEN:
				LeftMenuActivity.leftmenu_username_TextView
						.setText(R.string.leftmenu_username_default);
				LeftMenuActivity.logout_Button.setVisibility(View.GONE);
				iActivity.closeLoadingView();
				Toast.makeText(MobileApplication.mobileApplication,
						R.string.nologin, Toast.LENGTH_SHORT).show();
				break;
			case NetUtils.TimeOut:
				iActivity.closeLoadingView();
				Toast.makeText(MobileApplication.mobileApplication,
						R.string.request_timeout, Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
			return false;
		}
	});

}
